import apis from '@/api/index.ts'
import { Api, ApiType } from '@/api/type'

type ApisConfig = {
    'writeConfig'?:ApiType,
    'meetConfig'?:ApiType,
    'writeCode'?:ApiType,
}
interface preType  {
    'writeConfig'?:ApiType,
    'meetConfig'?:ApiType,
    'writeCode'?:ApiType, 
}

const useHttp = async (url:keyof Api)=>{
    const res = request1()
    const config = res[url] as ApiType
    return eval(await http(config))
}

const request1 = request()

export default useHttp

 function request(){
    
   let apisConfig:ApisConfig
   return  function():ApisConfig{
    if(apisConfig){
        return apisConfig
    } 
    apisConfig =  initApi() as ApisConfig
    console.log(apisConfig);
    
    return apisConfig
   }
}

/**
 * desc:生成API调用函数
 */
 function initApi(){
    const requestData = apis.reduce((pre:preType,cur:ApiType)=>{
        console.log(pre);
        const name = cur.name as keyof ApisConfig
        pre[name] = cur
        return pre
    },{})
    return requestData
}

/**
 * desc:模拟封装请求
 */
function http(config:ApiType) {
   const url = `data/${config.name}.js`
   return fetch(url,{
    method:'get'
   }).then(res=>{
    return res.text()
    }).then(data=>{
        return data
    })
}